﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.IO;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Data;
using ThoughtWorks.QRCode.Codec.Util;
using System.Text.RegularExpressions;

namespace FormsAppT8
{
    public partial class FormT8BCDtest : Form
    {

        //dbconn db = new dbconn();

        public FormT8BCDtest()
        {
            InitializeComponent();
        }
        private UserSQLClass usql = new UserSQLClass();
        private SqlConnection Mycon;


        //public void mx()
        //{
        //    string sql = "select a.RowNo,a.CU_KHCGDDH,b.MaterialId,b.MaterialName,b.MaterialSpec,a.SQuantity,a.Remark,a.CU_count,a.BPMaterialId from salDispatchListDetail a,comMaterialGroup b where a.SupplyOrgId='" + label34.Text + "' and a.billno='" + label30.Text + "' and a.MaterialId=b.MaterialId";
        //    //string sql = "select a.RowNo,'',b.MaterialId,b.MaterialName,b.MaterialSpec,a.SQuantity,a.Remark,'0',a.BPMaterialId from salDispatchListDetail a,comMaterialGroup b where a.SupplyOrgId='" + flag + "' and a.billno='" + billno + "' and a.MaterialId=b.MaterialId";
        //    dataGridView1.Rows.Clear();
        //    db.databind(sql, "salDispatchListDetail", dataGridView1);
        //    for (int i = 0; i < dataGridView1.RowCount; i++)
        //    {
        //        dataGridView1.Rows[i].Cells[5].Value = Convert.ToDouble(dataGridView1.Rows[i].Cells[5].Value.ToString());
        //        dataGridView1.Rows[i].Cells[7].Value = Convert.ToDouble(dataGridView1.Rows[i].Cells[7].Value.ToString());
        //        //dataGridView1.Rows[i].Cells[7].Value = "0";
        //    }
        //}

        /// <summary>
        /// 打印执行
        /// </summary>
        public void dy()
        {
            //printDialog1.Document = printDocument1;
            //if (printDialog1.ShowDialog() == DialogResult.OK)
            //{
            //设置打印时横向还是纵向
            //printDocument1.PrinterSettings.Copies = Convert.ToInt16(comboBox1.Text);
            printDocument1.PrinterSettings.Copies = 1;
            printDocument1.DefaultPageSettings.Landscape = false;
            printDocument1.DefaultPageSettings.Margins = new Margins(20, 20, 20, 0);
            PrintDocument prtdoc = new PrintDocument();
            printDocument1.PrinterSettings.PrinterName = prtdoc.PrinterSettings.PrinterName;
            printDocument1.Print();
            Thread.Sleep(100);
            //string sql = "update salDispatchListDetail set cu_count=cu_count+1 where billno='" + label30.Text + "' and rowno='" + label33.Text + "'";
            //db.sqlcommand(sql);
            // }
        }

        private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            Bitmap _NewBitmap = new Bitmap(panel1.Width, panel1.Height);
            panel1.DrawToBitmap(_NewBitmap, new Rectangle(0, 0, _NewBitmap.Width, _NewBitmap.Height));
            e.Graphics.DrawImage(_NewBitmap, 0, 0, _NewBitmap.Width, _NewBitmap.Height);
        }

        private void FormT8BCD_Load(object sender, EventArgs e)
        {
            Mycon = new SqlConnection(usql.ConfigGetValue111());
            comboBox2.SelectedItem = comboBox2.Items[0];
            textBox6.Text = DateTime.Now.Date.ToString("yyyy-MM-dd");      
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            int n, m,m1,mn;
            m = Convert.ToInt32(textBox7.Text);
            m1 = Convert.ToInt32(textBox15.Text);
            n = m / m1;
            mn = m % m1;

            string text1= textBox1.Text;
            string text15=textBox15.Text;
            byte nnn=Convert.ToByte(comboBox1.Text.Trim());
            //重复打印多份
            for (int j = 0; j < nnn; j++)
            {
                textBox1.Text = text1;
                textBox15.Text = text15;
                ewmsc();
                Application.DoEvents();
                //数量分标
                for (int i = 0; i < n; i++)
                {
                    dy();
                    getCodeAdd();
                    barcodeControl3.Data = textBox1.Text;
                    barcodeControl1.Data = textBox1.Text;
                }
                if (mn > 0)
                {
                    textBox15.Text = mn.ToString();
                    ewmsc();
                    Application.DoEvents();
                    dy();
                }
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (comboBox2.SelectedIndex >= 0 && comboBox2.SelectedIndex < 4)
            {
                //连接数据库
                //SqlConnection con = new SqlConnection("server=服务器名称;database=数据库名称;user id=登录名;pwd=登录密码;");
                                
                //调用存储过程
                SqlCommand scd = new SqlCommand("AAcu_GetBill", Mycon);
                scd.CommandType = CommandType.StoredProcedure;//调用命令改成存储格式，若上个语句中是SQL语句则不用这一句
                                                              //如存储过程带参数，怎需要向存储过程传参，否则不需要下面
                SqlParameter para0 = new SqlParameter("@type", SqlDbType.Int);//参数名称，类型，大小
                para0.Value = comboBox2.SelectedIndex;
                scd.Parameters.Add(para0);                
                SqlParameter para1 = new SqlParameter("@billNo", SqlDbType.VarChar, 40);
                para1.Value = textBox8.Text.Trim();
                scd.Parameters.Add(para1);
                SqlParameter para2 = new SqlParameter("@bizPartner", SqlDbType.VarChar, 100);
                para2.Value = textBox9.Text.Trim();
                scd.Parameters.Add(para2);
                SqlParameter para3 = new SqlParameter("@billDateS", SqlDbType.Int);
                para3.Value = int.Parse(dateTimePicker1.Value.Date.ToString("yyyyMMdd"));
                scd.Parameters.Add(para3);
                SqlParameter para4 = new SqlParameter("@billDateE", SqlDbType.Int);
                para4.Value = int.Parse(dateTimePicker2.Value.Date.ToString("yyyyMMdd"));
                scd.Parameters.Add(para4);
                SqlParameter para5 = new SqlParameter("@material", SqlDbType.VarChar, 100);
                para5.Value = textBox10.Text.Trim();
                scd.Parameters.Add(para5);
                SqlParameter para6 = new SqlParameter("@materialSpec", SqlDbType.VarChar, 100);
                para6.Value = textBox11.Text.Trim();
                scd.Parameters.Add(para6);
                SqlParameter para7 = new SqlParameter("@BPMaterial", SqlDbType.VarChar, 100);
                para7.Value = textBox12.Text.Trim();
                scd.Parameters.Add(para7);
                try
                {
                    //打开数据库
                    if (Mycon.State == ConnectionState.Closed)
                    {
                        Mycon.Open();
                    }
                    //执行存储过程
                    //scd.ExecuteNonQuery();
                    //如果想把结果用DataGridView显示出来，需要以下步骤
                    SqlDataAdapter sda = new SqlDataAdapter(scd);
                    DataSet dt = new DataSet();//新建一个临时表存放结果
                    sda.Fill(dt);
                    dataGridView1.DataSource = dt.Tables[0].DefaultView;//如果有多个返回结果，可以改变Tables[0]里面的参数0，显示需要的返回结果

                    //dataGridView1.Columns["CreateTime"].Visible = false;
                    //dataGridView1.Columns["CurrentState"].Visible = false;
                    //dataGridView1.Columns["Column1"].DisplayIndex = 3;

                    if (dt.Tables[0].Rows.Count < 1)
                    {
                        MessageBox.Show("指定条件内，无有效记录！", "信息提示",
                             MessageBoxButtons.OK, MessageBoxIcon.None);
                    }
                    else
                    {
                        string bill = dt.Tables[0].Rows[0]["BillNo"].ToString();
                        setDataGridView2(bill);
                    }
                }
                finally
                {
                    //关闭数据库
                    if (Mycon.State != ConnectionState.Closed)
                    {
                        Mycon.Close();
                    }
                }

            }
            else
            {
                MessageBox.Show("单据类型未选择或者不存在,请选择后操作！", "信息提示",
                               MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }        

        private void button3_Click(object sender, EventArgs e)
        {
            comboBox2.SelectedItem = comboBox2.Items[0];
            textBox8.Text = "";
            textBox9.Text = "";
            textBox10.Text = "";
            textBox11.Text = "";
            textBox12.Text = "";
            dateTimePicker1.Value = DateTime.Now;
            dateTimePicker2.Value = DateTime.Now;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ewmsc();
        }
        private void setDataGridView2(string bill)
        {
            //调用存储过程
            SqlCommand scd = new SqlCommand("AAcu_GetBillInfo", Mycon);
            scd.CommandType = CommandType.StoredProcedure;//调用命令改成存储格式，若上个语句中是SQL语句则不用这一句
                                                          //如存储过程带参数，怎需要向存储过程传参，否则不需要下面
            SqlParameter para0 = new SqlParameter("@type", SqlDbType.Int);//参数名称，类型，大小
            para0.Value = comboBox2.SelectedIndex;
            scd.Parameters.Add(para0);
            SqlParameter para1 = new SqlParameter("@billNo", SqlDbType.VarChar, 40);
            para1.Value = bill;
            scd.Parameters.Add(para1);
            SqlParameter para5 = new SqlParameter("@material", SqlDbType.VarChar, 100);
            para5.Value = textBox10.Text.Trim();
            scd.Parameters.Add(para5);
            SqlParameter para6 = new SqlParameter("@materialSpec", SqlDbType.VarChar, 100);
            para6.Value = textBox11.Text.Trim();
            scd.Parameters.Add(para6);
            SqlParameter para7 = new SqlParameter("@BPMaterial", SqlDbType.VarChar, 100);
            para7.Value = textBox12.Text.Trim();
            scd.Parameters.Add(para7);
            try
            {
                //打开数据库
                if (Mycon.State == ConnectionState.Closed)
                {
                    Mycon.Open();
                }
                //执行存储过程
                //scd.ExecuteNonQuery();
                //如果想把结果用DataGridView显示出来，需要以下步骤
                SqlDataAdapter sda = new SqlDataAdapter(scd);
                DataSet dt = new DataSet();//新建一个临时表存放结果
                sda.Fill(dt);
                dataGridView2.DataSource = dt.Tables[0].DefaultView;//如果有多个返回结果，可以改变Tables[0]里面的参数0，显示需要的返回结果

                if (dt.Tables[0].Rows.Count < 1)
                {
                    MessageBox.Show("当前单据中指定条件内，无有效记录！", "信息提示",
                         MessageBoxButtons.OK, MessageBoxIcon.None);
                }
                else if (dataGridView2.SelectedRows.Count > 0)
                {

                }
            }
            finally
            {
                //关闭数据库
                if (Mycon.State != ConnectionState.Closed)
                {

                    Mycon.Close();
                }
            }
        }


        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                string bill = "";
                bill = dataGridView1.SelectedRows[0].Cells["OrderNo"].Value.ToString();
                setDataGridView2(bill);
            }
        }

        private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView2.SelectedRows.Count > 0)
            {
                textBox2.Text = dataGridView2.SelectedRows[0].Cells["OrderNoB"].Value.ToString();
                textBox3.Text = dataGridView2.SelectedRows[0].Cells["MaterialNo"].Value.ToString();
                textBox13.Text = dataGridView2.SelectedRows[0].Cells["MaterialName"].Value.ToString();
                textBox4.Text = dataGridView2.SelectedRows[0].Cells["MaterialSpec"].Value.ToString();
                textBox14.Text = dataGridView2.SelectedRows[0].Cells["CustomerNameM"].Value.ToString();
                textBox7.Text = dataGridView2.SelectedRows[0].Cells["TotalQty"].Value.ToString();
                textBox15.Text = textBox7.Text;
                textBox1.Text = getCode();
                textBox5.Text = getBach();
            }
        }

        private void dataGridView2_DataSourceChanged(object sender, EventArgs e)
        {
            if (dataGridView2.SelectedRows.Count > 0)
            {
                textBox2.Text = dataGridView2.SelectedRows[0].Cells["OrderNoB"].Value.ToString();
                textBox3.Text = dataGridView2.SelectedRows[0].Cells["MaterialNo"].Value.ToString();
                textBox13.Text = dataGridView2.SelectedRows[0].Cells["MaterialName"].Value.ToString();
                textBox4.Text = dataGridView2.SelectedRows[0].Cells["MaterialSpec"].Value.ToString();
                textBox14.Text = dataGridView2.SelectedRows[0].Cells["CustomerNameM"].Value.ToString();
                textBox7.Text = dataGridView2.SelectedRows[0].Cells["TotalQty"].Value.ToString();
                textBox15.Text = textBox7.Text;
                textBox1.Text = getCode();
                textBox5.Text = getBach();
            }
        }

        /// <summary>
        /// 自动生成序列条码
        /// </summary>
        /// <returns></returns>
        private string getCode()
        {
            string str="C"+ DateTime.Now.Date.ToString("yyMMdd");
            string user= loginTxtWR.GetV("//users", "user");
            string userNum = loginTxtWR.GetV("//users", "userNum");
            str = str + user + userNum;
            return str;
        }

        /// <summary>
        /// 自动生成序列条码自增
        /// </summary>
        /// <returns></returns>
        private string getCodeAdd()
        {
            string str = textBox1.Text;
            string nstr = "";
            if(textBox1.Text.Length>10)
            {
                nstr = textBox1.Text.Substring(textBox1.Text.Length - 4);
                nstr = (Convert.ToInt32(nstr) + 1).ToString().PadLeft(4,'0');
            }
            str = str.Substring(0, textBox1.Text.Length - 4) + nstr;
            textBox1.Text = str;
            return str;
        }

        /// <summary>
        /// 自动生成批次
        /// </summary>
        /// <returns></returns>
        private string getBach()
        {
            string str = DateTime.Now.Date.ToString("yyMMdd");
            string user = "0";
            if (dataGridView1.SelectedRows.Count > 0)
            {
                user = dataGridView1.SelectedRows[0].Cells["CustomerNo"].Value.ToString();
            }
            //string userNum = loginTxtWR.GetV("//users", "userNum");
            str = str +"-"+ user +"-001";
            return str;
        }

        /// <summary>
        /// 生成二维码信息和标签信息
        /// </summary>
        public void ewmsc()
        {
            label1.Text ="物料代码："+ textBox3.Text;
            label18.Text = "物料名称：" + textBox13.Text;
            label19.Text = "规格型号：" + textBox4.Text;
            label20.Text = "客户品名：" + textBox14.Text;
            label21.Text = "数量：" + textBox15.Text + "PCS";
            label22.Text = "批次：" + textBox5.Text ;

            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeScale = 2;
            qrCodeEncoder.QRCodeVersion = 10;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;

            Image image;
            string data = textBox3.Text + "&" + textBox15.Text + "&" + textBox5.Text;
            image = qrCodeEncoder.Encode(data, Encoding.UTF8);

            pictureBox1.Image = image;
            pictureBox2.Image = image;

            label33.Text = label1.Text;
            label31.Text = label18.Text;
            label30.Text = label19.Text;
            label29.Text = label20.Text;
            label24.Text = label21.Text;
            label23.Text = label22.Text;

            Regex reg = new Regex("^[A-Za-z]\\d{9,16}$");//正则表达式
            if (reg.IsMatch(textBox1.Text))
            {
                barcodeControl1.BarcodeType = Cobainsoft.Windows.Forms.BarcodeType.CODE128A;
                barcodeControl3.BarcodeType = Cobainsoft.Windows.Forms.BarcodeType.CODE128A;
            }
            else
            {
                barcodeControl1.BarcodeType = Cobainsoft.Windows.Forms.BarcodeType.CODE93;
                barcodeControl3.BarcodeType = Cobainsoft.Windows.Forms.BarcodeType.CODE93;
            }
            barcodeControl3.Data = textBox1.Text;
            barcodeControl1.Data = textBox1.Text;

        }

    }
}
